package cn.zyjblogs.starter.sms.provider;

import cn.zyjblogs.starter.sms.common.SmsEnum;
import cn.zyjblogs.starter.sms.common.SmsRequest;
import cn.zyjblogs.starter.sms.common.SmsResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuyijun
 */
public class CompositeSmsGranter implements SmsGranter {
    private final List<SmsGranter> smsGranters;

    public CompositeSmsGranter(List<SmsGranter> smsGranters) {
        this.smsGranters = new ArrayList<>(smsGranters);
    }

    @Override
    public SmsGranter getGranter(SmsEnum smsEnum) {
        for (SmsGranter granter : smsGranters) {
            SmsGranter granters = granter.getGranter(smsEnum);
            if (granters != null) {
                return granters;
            }
        }
        return null;
    }

    @Override
    public SmsResponse sendSms(SmsEnum smsEnum, List<String> phones, SmsRequest smsRequest) {
        SmsGranter granter1 = getGranter(smsEnum);
        if (granter1 != null) {
            return granter1.sendSms(smsEnum, phones, smsRequest);
        }
        return null;
    }

    @Override
    public SmsResponse sendSms(SmsEnum smsEnum, String phone, SmsRequest smsRequest) {
        SmsGranter granter1 = getGranter(smsEnum);
        if (granter1 != null) {
            return granter1.sendSms(smsEnum, phone, smsRequest);
        }
        return null;
    }

    public void addTokenGranter(SmsGranter smsGranter) {
        if (smsGranter == null) {
            throw new IllegalArgumentException("sms granter is null");
        }
        smsGranters.add(smsGranter);
    }
}
